import { createSlice } from "@reduxjs/toolkit";

const bedMassage = createSlice({
    name: 'bed-massage',
    initialState: {
        bedlist:[]
    },
    reducers: {
        getBedData:(state,action)=>{
            state.bedlist=action.payload
            localStorage.setItem('bedlist', JSON.stringify(state.bedlist))
        },
        getAddBedList: (state, action) => {
            state.bedlist=state.bedlist.concat({
                id:state.bedlist.length,
                bednumber:action.payload.bednumber,
                department:action.payload.department,
                oxygen:action.payload.oxygen,
                heart:action.payload.heart,
                breath:action.payload.breath,
                icu:action.payload.icu,
                aircondition:action.payload.aircondition,
                tv:action.payload.tv,
                nurse:action.payload.nurse,
            })
            localStorage.setItem('bedlist', JSON.stringify(state.bedlist))
        },
        getBedListDel: (state, action) => {
            console.log(action.payload);
            state.bedlist = state.bedlist.filter((v: { id: number; }) => v.id !== action.payload)
            localStorage.setItem('bedlist', JSON.stringify(state.bedlist))
        },
        getBedListEdit: (state, action) => {
            const index = state.bedlist.findIndex((item: { id: any; }) => item.id === action.payload.id)
            if (index !== -1) {
                state.bedlist[index] = {
                    ...state.bedlist[index],
                    department: action.payload.department,
                    oxygen: action.payload.oxygen,
                    heart: action.payload.heart,
                    breath: action.payload.breath,
                    icu: action.payload.icu,
                    aircondition: action.payload.aircondition,
                    tv: action.payload.tv,
                    nurse: action.payload.nurse,
                }
            }
            localStorage.setItem('bedlist', JSON.stringify(state.bedlist))
        },
        getBedListSearch: (state, action) => {
            state.bedlist = state.bedlist.filter((item: any) => item.bednumber === action.payload)
        },
        getBedListReset: (state) => {
            state.bedlist = JSON.parse((localStorage as any).getItem('bedlist')) || [];
        }
    }
});

export const { getBedData,getBedListDel, getBedListEdit, getBedListSearch, getBedListReset, getAddBedList } = bedMassage.actions;
export default bedMassage.reducer;